package com.ruoyi.park.controller;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.park.domain.AdmittanceRecord;
import com.ruoyi.park.service.IAdmittanceRecordService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.util.Date;
import java.util.List;

/**
 * 在场车辆Controller
 *
 * @author 博雅
 * @date 2023-12-15
 */
@RestController
@RequestMapping("/park/AdmittanceRecord")
public class AdmittanceRecordController extends BaseController {
    @Autowired
    private IAdmittanceRecordService admittanceRecordService;

    /**
     * 查询在场车辆列表
     */
    @PreAuthorize("@ss.hasPermi('park:AdmittanceRecord:list')")
    @GetMapping("/list")
    public TableDataInfo list(AdmittanceRecord admittanceRecord) {
        startPage();
        List<AdmittanceRecord> list = admittanceRecordService.selectAdmittanceRecordList(admittanceRecord);
        return getDataTable(list);
    }

    /**
     * 导出在场车辆列表
     */
    @PreAuthorize("@ss.hasPermi('park:AdmittanceRecord:export')")
    @Log(title = "在场车辆", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, AdmittanceRecord admittanceRecord) {
        List<AdmittanceRecord> list = admittanceRecordService.selectAdmittanceRecordList(admittanceRecord);
        ExcelUtil<AdmittanceRecord> util = new ExcelUtil<AdmittanceRecord>(AdmittanceRecord.class);
        util.exportExcel(response, list, "在场车辆数据");
    }

    /**
     * 获取在场车辆详细信息
     */
    @PreAuthorize("@ss.hasPermi('park:AdmittanceRecord:query')")
    @GetMapping(value = "/{admittanceId}")
    public AjaxResult getInfo(@PathVariable("admittanceId") Long admittanceId) {
        return success(admittanceRecordService.selectAdmittanceRecordByAdmittanceId(admittanceId));
    }

    /**
     * 新增在场车辆
     */
    @PreAuthorize("@ss.hasPermi('park:AdmittanceRecord:add')")
    @Log(title = "在场车辆", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody AdmittanceRecord admittanceRecord) {
        return toAjax(admittanceRecordService.insertAdmittanceRecord(admittanceRecord));
    }

    /**
     * 修改在场车辆
     */
    @PreAuthorize("@ss.hasPermi('park:AdmittanceRecord:edit')")
    @Log(title = "在场车辆", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody AdmittanceRecord admittanceRecord) {
        return toAjax(admittanceRecordService.updateAdmittanceRecord(admittanceRecord));
    }

    /**
     * 删除在场车辆
     */
    @PreAuthorize("@ss.hasPermi('park:AdmittanceRecord:remove')")
    @Log(title = "在场车辆", businessType = BusinessType.DELETE)
    @DeleteMapping("/{admittanceIds}")
    public AjaxResult remove(@PathVariable Long[] admittanceIds) {
        return toAjax(admittanceRecordService.deleteAdmittanceRecordByAdmittanceIds(admittanceIds));
    }

    @RequestMapping("/getCarNo")
    public AjaxResult getCarNo(HttpServletRequest request) {

        StringBuffer jb = new StringBuffer();
        // JSONObject jsonObject;
        char[] lineChars = new char[1024 * 1024];
        char[] totalChars = new char[1024 * 1024];
        int readLen = 0;
        int totalLen = 0;
        try {
            BufferedReader reader = request.getReader();
            while ((readLen = reader.read(lineChars)) > 0) {
                for (int i = 0; i < readLen; i++) {
                    totalChars[totalLen + i] = lineChars[i];
                }
                totalLen += readLen;
            }
        } catch (Exception e) { /*report an error*/ }

        String lineStr = new String(totalChars);
        // 把接收到车牌结果保存到txt文件中
        //WriteTxt("d:\\plate_result.txt", lineStr);
        try {
            JSONObject jsonObject = JSON.parseObject(lineStr);
            if (jsonObject == null) {
                return null;
            }

            // 解析JSON数据，获取车牌号
            String license = jsonObject
                    .getJSONObject("AlarmInfoPlate")
                    .getJSONObject("result")
                    .getJSONObject("PlateResult")
                    .getString("license");
            if (license == null || license == "") {
                return null;
            }
            System.out.println("车牌号__" + license);

            //判断车牌是否黑名单，禁止入场


            //判断车辆是否在场
            if(!admittanceRecordService.admittanceIsExist(license)){
                //新增进场记录
                AdmittanceRecord admittanceRecord=new AdmittanceRecord();
                admittanceRecord.setAdmittanceTime(new Date());
                admittanceRecord.setCarNo(license);
                admittanceRecord.setCarStatus("1");
                admittanceRecordService.insertAdmittanceRecord(admittanceRecord);
            }else{//车子离场
                //查询车辆是否白名单，如果是白名单，计费为0元，直接开闸放行
                //查询车辆是否为绑定车位的车辆，计费为0元，直接开闸放行
                //如果是租赁车位，判断车位是否过期，如果已过期，按照普通车辆进行计费

                //更新出场记录
                AdmittanceRecord record=admittanceRecordService.getAdmittanceRecord(license);
                //计算停车费用，插入一条费用记录

                //用户支付停车费用，更新在场车辆状态，打开道闸


                //道闸关闭后，更新车辆状态和离场时间


 //               if(record.getCarStatus()=="2") {//车辆为支付状态，可以离场
//                    record.setLeaveTime(new Date());
//                    record.setCarStatus("3");
//                    admittanceRecordService.updateAdmittanceRecord(record);
//                }else{
//                    System.out.println("===================>车辆未支付停车费，禁止离场");
                    //计算停车费用

 //               }
            }
           // WriteTxt("d:\\plate_num.txt", license);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    //把json字符串以txt文件的形式保存
    protected void WriteTxt(String path, String txt) {
        try {
            FileWriter f = new FileWriter(path);
            BufferedWriter bw = new BufferedWriter(f);
            bw.write(txt);
            bw.close();
        } catch (Exception e) {
        }
    }

}
